package org.example.usercontroller;

import lombok.extern.slf4j.Slf4j;
import org.example.context.BaseContext;
import org.example.pojo.entity.AddressBook;
import org.example.pojo.Result;
import org.example.userservice.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user/addressbook")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @GetMapping("/list")
    public Result list(){
        AddressBook addressBook = new AddressBook();
        Long userid = BaseContext.getCurrentId();
        addressBook.setUserid(userid);
        List<AddressBook> list = addressService.list(addressBook);
        return Result.success(list);
    }

    @PostMapping("/add")
    public Result add(@RequestBody AddressBook addressBook){
        Long userid = BaseContext.getCurrentId();
        addressBook.setUserid(userid);
        log.info("add addressbook:{}", addressBook);
        addressService.insert(addressBook);
        return Result.success();
    }

    @PutMapping()
    public Result update(@RequestBody AddressBook addressBook){
        addressService.update(addressBook);
        return Result.success();
    }

    @PutMapping("/default")
    public Result setdefault(@RequestBody AddressBook addressBook){
        addressService.setDefault(addressBook);
        return Result.success();
    }

    @GetMapping("/default")
    public Result getdefault(){
        AddressBook addressBook = new AddressBook();
        Long userid = BaseContext.getCurrentId();
        addressBook.setUserid(userid);
        addressBook.setIsdefault(1);
        log.info("get default addressbook:{}", addressBook);
        List<AddressBook> list = addressService.list(addressBook);
        if(list.size()>0){
            return Result.success(list.get(0));
        }else{
            return Result.error("没有查询到默认地址");
        }
    }
}
